#coding=utf-8
__author__ = 'aesop'

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
#json lib has a big problem
#when given a utf-8 string
#it will return a string
#that transfers unicode string to hex form
#
#so it'll be fixed if using this
class json_aesop:
    def __init__(self, dic):
        self.__dic = dic;

    @staticmethod
    def encode(dic):
        return json_aesop(dic).json_encode()

    def json_encode(self):
        return self.__json_encode(self.__dic, "")[0:-1]

    def __json_encode(self,dic, index):
        str = ""

        if(isinstance(dic, dict)):
            it = iter(dic)
            try:
                 if(index !=""):
                         str += self.__trans_value_index(index) +  ':{'
                 else:
                        str += "{"
                 while(True):

                    val = it.next()
                    str += self.__json_encode(dic[val], val)
            except StopIteration:
                pass
            return str[0:-1] + "},"

        elif(isinstance(dic,list) or isinstance(dic,tuple)  ):
            str = ""
            if(not len(dic)):
                if(index !=""):
                         return self.__trans_value_index(index) +  ':[],'
                else:
                         return "[],"

            it = iter(dic)
            if(index !=""):
                         str += self.__trans_value_index(index) +  ':['
            else:
                        str += "["
            try:
                while(True):
                    val = it.next()

                    str +=  self.__json_encode(val,"")
            except StopIteration:
                pass
            return  str[0:-1] +  '],'
        else:
            if(index == 0 or index ==""):
                 str +=  self.__trans_value(dic)
            else:
                str += self.__trans_value_index(index)  +":"+ self.__trans_value(dic)
            return str



    def __trans_value(self,value):

        if(isinstance(value, int)):
            return  bytes(value) + ','
        '没见过这么傻逼的语言，默认使用单引号当字符串标识，单引号里面的\还是会转义 '
        return '"' + (bytes(value)).replace('"','\\\"').replace('\'','\\\"') + '",'

    def __trans_value_index(self, value):
        if(isinstance(value, basestring)):
            return '"' + value + '"'
        return bytes(value)


if __name__ == "__main__":
    p = u'你好fdsfsdf"'
    print p.replace('"','\\\"')

